<template>
  <div v-if="timeOutFlag">{{ newTime }}</div>
  <div v-else>{{ timeOutStr }}</div>
</template>
<script>
export default {
  name: 'count-down',
  props: {
    date: {
      type: [String, Date],
      default () {
        return new Date();
      }
    },
    // 时间间隔 单位:毫米
    timeSpace: {
      type: Number,
      default: 50
    },
    formatter: {
      type: [String, Function],
      default () {
        return ({ d, h, m, s, hm }) => {
          return '距离下班还有：' + d + '天' + h + '小时' + m + '分钟' + s + '秒' + hm + '毫秒'
        }
      }
    },
    timeOutStr: {
      type: String,
      default: '已经下班了！蠢货！'
    }
  },
  data () {
    return {
      newTime: '',
      timeOutFlag: false,
      timeInterval: null
    };
  },
  methods: {
    TimeTo (dd) {
      this.timeOutFlag = true;
      const t = new Date(dd); // 取得指定时间的总毫秒数
      const n = new Date().getTime(); // 取得当前毫秒数
      const c = t - n; // 得到时间差
      if (c <= 0) {
        this.timeOutFlag = false;
        this.clearTimeFn();
        this.$emit('timeEnd')
        return; // 结束执行
      }
      let d = parseInt(c / 1000 / 60 / 60 / 24); // 相差的天数
      let h = parseInt(c / 1000 / 60 / 60 - 24 * d); // 相差的小时
      let m = parseInt(c / 1000 / 60 - 24 * 60 * d - 60 * h); // 相差的分钟数
      let s = parseInt(c / 1000 - 24 * 60 * 60 * d - 60 * 60 * h - 60 * m); // 相差的秒数
      let hm = Math.floor((c - 24 * 60 * 60 * 1000 * d - 60 * 60 * 1000 * h - 60 * 1000 * m - s * 1000) / 10);
      this.newTime = this.formatter({ d, h, m, s, hm });
    },
    clearTimeFn () {
      if (this.timeInterval) {
        clearInterval(this.timeInterval); //清除计时器
        this.timeInterval = null;
      }
    }
  },
  watch: {
    date: {
      handler (val) {
        if (!val) return
        this.timeInterval = setInterval(() => {
          this.TimeTo(this.date);
        }, this.timeSpace)
      },
      // 一进页面就执行
      immediate: true
    }
  },
  beforeDestroy () {
    this.clearTimeFn();
  }
};
</script>
